package com.gitee.ixtf.sap

import cn.hutool.log.Log
import com.gitee.ixtf.guice.Jguice
import com.gitee.ixtf.vertx.verticle.BaseMainVerticle
import io.vertx.core.DeploymentOptions
import io.vertx.core.Launcher
import io.vertx.core.Vertx
import io.vertx.core.VertxOptions
import io.vertx.kotlin.coroutines.coAwait
import kotlin.system.exitProcess
import kotlin.time.Duration.Companion.hours
import kotlinx.coroutines.runBlocking

fun main(args: Array<String>) {
  ServiceLauncher().dispatch(args)
}

open class ServiceLauncher : Launcher() {
  override fun getMainVerticle(): String = BaseMainVerticle::class.java.name

  override fun beforeStartingVertx(options: VertxOptions) {
    with(options) { maxWorkerExecuteTime = 1.hours.inWholeNanoseconds }
  }

  override fun afterStartingVertx(vertx: Vertx) {
    super.afterStartingVertx(vertx)
    Runtime.getRuntime().addShutdownHook(Thread { runBlocking { vertx.close().coAwait() } })
    Jguice.init(ServiceModule(vertx))
  }

  override fun handleDeployFailed(
      vertx: Vertx,
      mainVerticle: String,
      deploymentOptions: DeploymentOptions,
      cause: Throwable
  ) {
    Log.get().error(cause, "handleDeployFailed $mainVerticle")
    super.handleDeployFailed(vertx, mainVerticle, deploymentOptions, cause)
    exitProcess(1)
  }
}
